package com.blog.study.study7;

/**
 * 〈线程安全性问题〉<br>
 *
 * @author 未绪
 * @time 2017/12/3 9:01
 */
public class SafetyThread {

    public static void main(String[] args) {
        new SafetyThread().init();
    }

    public void init() {
        MySafetyThread t1 = new MySafetyThread("我是来自东土大唐的欧阳先生");
        MySafetyThread t2 = new MySafetyThread("我是来自西域的上官小姐");
        Thread thread1 = new Thread(t1);
        Thread thread2 = new Thread(t2);

        thread1.start();
        thread2.start();
    }

}

class MyUnSafetyThread implements Runnable {

    private String threadName;

    public MyUnSafetyThread(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        while (true) {
//            try {
//                Thread.sleep(300);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            for (int i = 0; i < threadName.length(); i++) {
                System.out.print(this.threadName.charAt(i));
            }
            System.out.println();
        }
    }
}


class MySafetyThread implements Runnable {

    private static final String CLOCK="CLOCK";      //声明一个静态变量作为锁
    private String threadName;

    public MySafetyThread(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        while (true) {
//            try {
//                Thread.sleep(300);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
            synchronized (SafetyThread.class) {//只能使用同一个对象作为同步锁
                for (int i = 0; i < threadName.length(); i++) {
                    System.out.print(this.threadName.charAt(i));
                }
                System.out.println();
            }
        }

    }
}